package com.mooc.fuxi.ui.comment;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.mooc.fuxi.DaoMaster;
import com.mooc.fuxi.DaoSession;
import com.mooc.fuxi.R;
import com.mooc.fuxi.entity.CommentEntity;

import java.util.List;

public class CommentActivity extends AppCompatActivity implements OnItemChildClickListener {

    private TextView comment_title_tv;
    private RecyclerView comment_rv;
    private String title;
    private CommentAdapter adapter=new CommentAdapter();
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_comment);
        title = getIntent().getStringExtra("title");
        init();
        initData();
    }

    private void init(){
        comment_title_tv = findViewById(R.id.comment_title_tv);
        comment_title_tv.setText(title);
        comment_rv = findViewById(R.id.comment_rv);
        LinearLayoutManager manager = new LinearLayoutManager(this);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        comment_rv.setLayoutManager(manager);
        adapter.setOnItemChildClickListener(this);
        comment_rv.setAdapter(adapter);
    }

    private void initData(){
        DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(this,"user.db");
        DaoMaster master = new DaoMaster(helper.getWritableDb());
        DaoSession session = master.newSession();
        List<CommentEntity>list = session.queryBuilder(CommentEntity.class).list();
//        adapter.setNewInstance(list);
        adapter.addData(list);
        Log.e("ZXY","CommentActivity:"+list.size());
        Log.e("ZXY","CommentActivity:"+adapter.getData().size());
        for (CommentEntity entity : list){
            Log.e("ZXY","initData()"+entity.title+entity.flag);
        }
    }


    @Override
    public void onItemChildClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
//        this.adapter.getItem(position).flag = !this.adapter.getItem(position).flag;
        CommentEntity entity =  this.adapter.getItem(position);
        entity.flag = !entity.flag;
        this.adapter.setData(position,entity);
        DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(this,"user.db");
        DaoMaster master = new DaoMaster(helper.getWritableDb());
        DaoSession session = master.newSession();
        session.update(this.adapter.getItem(position));
    }
}
